package http;

import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;

import java.net.HttpCookie;
import java.util.List;
import java.util.Scanner;

public class ChatGpt {

    private static String URL =
            "https://api.openai.com/v1/chat/completions";

    private static String Key = "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";


    public static void main(String[] args) {
        HttpRequest request = HttpUtil.createPost(URL)
                .header("Authorization", "Bearer " + Key);
        request.timeout(10 * 1000);
        request.setHttpProxy("127.0.0.1", 33210);
        //request.setRest()
        //{
        //  "model": "gpt-3.5-turbo",
        //  "messages": [{"role": "user", "content": "Hello!"}]
        //}
        Dict bodyMap = new Dict();
        bodyMap.set("model", "gpt-3.5-turbo");
        bodyMap.set("messages", JSONUtil.parseArray("[{\"role\": \"user\", \"content\": \"Hello!\"}]"));

        boolean first = true;
        while (true) {
            System.out.println("请输入你的问题？");
            Scanner scanner = new Scanner(System.in);
            String next = scanner.next();
            bodyMap.set("messages", JSONUtil.parseArray(
                    StrUtil.format("[{\"role\": \"user\", \"content\": \"{}\"}]", next)));
            String jsonStr = JSONUtil.toJsonStr(bodyMap);
            request.body(jsonStr);
            System.out.println(" 发送..." + jsonStr + "\n" + request.contentLength());
            HttpResponse response = request.execute();

            if (first) {
                List<HttpCookie> cookies = response.getCookies();
                request.cookie(cookies);
                first = false;
            }
            String body = response.body();
            System.out.println("body = " + body);
            Object byPath = JSONUtil.parseObj(body).getByPath("choices[0].message.content");
            System.err.println(byPath);
        }
    }
}
